package com.jeeboot.modules.app.service;


import com.jeeboot.modules.app.dao.UserDao;
import com.jeeboot.modules.app.entity.UserEntity;
import com.jeeboot.system.common.exception.RRException;
import com.jeeboot.system.common.validator.Assert;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * Created by IntelliJ IDEA.
 * 作者: 李哲训
 * 邮箱：370261528@qq.com
 * QQ群：571785017
 * 时间: 2017/11/29
 * 功能:登录用户信息
 */
@Service("userService")
public class UserService {

    @Autowired
    private UserDao userDao;


    public UserEntity queryObject(Long userId) {
        return userDao.findById(userId).get();
    }


    public Long queryTotal() {
        return userDao.count();
    }


    public void save(String mobile, String password) {
        UserEntity user = new UserEntity();
        user.setMobile(mobile);
        user.setUsername(mobile);
        user.setPassword(DigestUtils.sha256Hex(password));
        user.setCreateTime(new Date());
        userDao.save(user);
    }


    public void update(UserEntity user) {
        userDao.save(user);
    }


    public void delete(Long userId) {
        userDao.delete(queryObject(userId));
    }


    public void deleteBatch(Long[] userIds) {
        for (Long userId : userIds) {
            delete(userId);
        }
    }


    public UserEntity queryByMobile(String mobile) {
        return userDao.findByMobile(mobile);
    }


    public long login(String mobile, String password) {
        UserEntity user = queryByMobile(mobile);
        Assert.isNull(user, "手机号或密码错误");

        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(password))) {
            throw new RRException("手机号或密码错误");
        }

        return user.getUserId();
    }
}
